/*
 * @Description: 
 * @Author: HuRrongChao
 * @Date: 2025-01-14 16:59:10
 * @LastEditors: HuRrongChao
 * @LastEditTime: 2025-01-15 16:59:24
 */
export class Barrage {
  constructor(options, ctx) {
    this.ctx = ctx
    this.isInit = false // 是否初始化
    this.flag = true // 是否已经出现过
    Object.assign(this, options)
  }

  getWidth() {
    const span = document.createElement('span')
    span.innerText = this.value
    span.style.font = this.fontSize + 'px "Microsoft YaHei"'
    span.style.position = 'absolute'
    span.style.zIndex = -1

    document.body.appendChild(span)
    let width = span.clientWidth
    document.body.removeChild(span)

    return width
  }

  init() {
    // 初始化弹幕
    this.color = this.color || this.ctx.color
    this.fontSize = this.fontSize || this.ctx.fontSize
    this.speed = this.speed || this.ctx.speed
    // 获取弹幕宽度
    this.width = this.getWidth()

    this.x = this.ctx.canvas.width

    this.y = Math.random() * this.ctx.canvas.height

    if (this.y > this.ctx.height - this.fontSize) {
      this.y = this.ctx.height - this.fontSize
    }

    if (this.y < this.fontSize) {
      this.y = this.fontSize
    }
  }

  render() {
    this.ctx.context.font = this.fontSize + 'px "Microsoft YaHei"'
    this.ctx.context.fillStyle = this.color
    this.ctx.context.fillText(this.value, this.x, this.y)
  }
}